package com.example.srm.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.srm.auth.anno.Authority;
import com.example.srm.auth.service.SysUserTokenService;
import com.example.srm.constant.PermissionConstant;
import com.example.srm.constant.SysUserTokenConstant;
import com.example.srm.constant.UserConstant;
import com.example.srm.domain.SysUserToken;
import com.example.srm.domain.TRole;
import com.example.srm.domain.TUser;
import com.example.srm.domain.vo.PageView;
import com.example.srm.domain.vo.Result;
import com.example.srm.auth.service.TRoleService;
import com.example.srm.auth.service.TUserRoleService;
import com.example.srm.auth.service.TUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author pfk
 * @creatTime 2021/11/24 19:04
 * @describe    用户操作
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    private TUserService userService;
    @Autowired
    private TRoleService roleService;
    @Autowired
    private TUserRoleService userRoleService;
    @Autowired
    private SysUserTokenService tokenService;

    /**
     * 获取当前登录用户
     * @return
     */
    @RequestMapping(value = "/current_user",method = RequestMethod.GET)
    public Result getCurrentUser(HttpServletRequest request) throws Exception {
        String token = request.getHeader(PermissionConstant.AUTH_TOKEN);
        //根据token查询用户信息
        TUser user = userService.getUserByToken(token);
        System.out.println("查询用户信息："+user);
        return new Result().setData(user).setSuccess(true);
    }

    /**
     * 展示用户信息
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "",method = RequestMethod.GET)
    @Authority(auth = "account:user:list")
    public Result Query(Integer page,Integer pageSize) throws Exception {
        //校验参数是否合法
        if (page==null||page<0){
            page=1;
        }
        if (pageSize==null||pageSize<=0){
            pageSize=10;
        }
        //分页查询
        Page<TUser> userPage = userService.page(new Page<>(page,pageSize),new QueryWrapper<TUser>().orderByDesc(UserConstant.createTime));
        PageView<TUser> pageView = new PageView<TUser>()
                .setRows(userPage.getRecords())
                .setTotalCount(userPage.getTotal())
                .setTotalPage(new Integer(userPage.getPages()+""));

        return new Result().setSuccess(true).setData(pageView);
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @RequestMapping(value = "",method = RequestMethod.POST)
    @Authority(auth = "account:user:add")
    public Result save(@RequestBody TUser user){
        if (user.getUserName() == null || user.getPassword() == null){
            return new Result().setMsg("参数不合法");
        }
        TUser userOne = userService.getOne(new QueryWrapper<TUser>().eq(UserConstant.name, user.getUserName()));
        if (userOne!=null) {
            return new Result().setMsg("用户"+userOne.getUserName()+"已经存在");
        }
        //设置用户状态 开启
        user.setState("1");
        user.setCreateTime(new Date());
        if(StringUtils.isEmpty(user.getType())) {
            //设置用户类型 默认为普通用户
            user.setType("user");
        }
        //对密码进行加盐
        String password = user.getPassword();
        String salt = UUID.randomUUID().toString().replace("-","");
        user.setSalt(salt);
        password = new Md5Hash(password, salt).toString();
        user.setPassword(password);
        boolean save = userService.save(user);
        return new Result().setSuccess(save);
    }

    /**
     * 完善用户信息
     * @param userView
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "",method = RequestMethod.PUT)
    @Authority(auth = "account:user:update")
    public Result completeInfo(@RequestBody TUser userView, HttpServletRequest request) throws Exception {
        //判断修改的用户是否存在
        TUser idUser = userService.getOne(new QueryWrapper<TUser>().eq(UserConstant.id, userView.getId()));
        if (idUser==null) {
            return new Result().setMsg("用户"+userView.getUserName()+"不存在");
        }
        TUser nameUser = userService.getOne(new QueryWrapper<TUser>()
                .eq(UserConstant.name, userView.getUserName())
                .ne(UserConstant.id,userView.getId()));
        if (nameUser!=null) {
            return new Result().setMsg("用户名"+userView.getUserName()+"已经存在");
        }
        boolean updateById = userService.updateById(userView);
        //刷新session中的用户信息
//        HttpSession session = request.getSession();
//        TUser userinfo = (TUser) session.getAttribute("USERINFO");
//        if (userinfo.getId().equals(userView.getId())){
//            session.setAttribute("USERINFO",userView);
//            session.setMaxInactiveInterval(60*5);
//        }
        return new Result().setSuccess(updateById);
    }


    /**
     * 根据用户名删除用户
     * @param userName
     * @return
     */
    @RequestMapping(value = "",params = "userName",method = RequestMethod.DELETE)
    @Authority(auth = "account:user:delete")
    public Result deleteByName(String userName){
        if (userName==null){
            return new Result().setMsg("用户名不能为空");
        }
        TUser user = userService.getOne(new QueryWrapper<TUser>().eq(UserConstant.name,userName));
        if (user==null) {
            return new Result().setMsg("用户不存在");
        }
        //查询用户的角色中是否存在超级管理员
        List<TRole> roleList = userService.getRolesByUserId(user.getId());
        boolean isAdmin = roleList.stream().anyMatch(e -> "超级管理员".equals(e.getName()));
        if (user.getType().equals("admin")||isAdmin){
            return new Result().setMsg("超级管理员不能被删除");
        }
        boolean remove = userService.remove(new QueryWrapper<TUser>().eq(UserConstant.name, userName));
        return new Result().setSuccess(remove);
    }

    /**
     * 用户状态修改
     * @param userView
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/status",method = RequestMethod.PUT)
    @Authority(auth = "account:user:status")
    public Result updateStatus(@RequestBody TUser userView) throws Exception {
        if (userView.getId()==null){
            return new Result().setMsg("用户id不能为空");
        }
        TUser user = userService.getById(userView.getId());
        //查询用户的角色中是否存在超级管理员
        List<TRole> roleList = userService.getRolesByUserId(user.getId());
        boolean isAdmin = roleList.stream().anyMatch(e -> "超级管理员".equals(e.getName()));
        if (user.getType().equals("admin")||isAdmin){
            return new Result().setMsg("非法操作,超级管理员不能被禁用");
        }
        boolean update = userService.updateById(userView);
        return new Result().setSuccess(update);
    }

    /**
     * 根据Id获取用户
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "",params = "id",method = RequestMethod.GET)
    public Result findById(String id) throws Exception {
        if (id==null){
            return new Result().setMsg("用户id不能为空");
        }
        TUser user = userService.getById(id);
        if (user==null){
            return new Result().setMsg("用户不存在");
        }
        //防止密码泄露，将返回的用户信息改为null
        user.setPassword(null);
        return new Result().setSuccess(true).setData(user);
    }

    /**
     * 修改密码
     * @return
     */
    @RequestMapping(value = "/password",method = RequestMethod.PUT)
    @Authority(auth = "account:user:password")
    public Result updatePassword(@RequestBody Map<String,Object> map){
        if (map.get("userName")==null||map.get("password")==null) {
            return new Result().setMsg("参数不合法");
        }
        String password = (String) map.get("password");
        TUser user = userService.getOne(new QueryWrapper<TUser>().eq(UserConstant.name,map.get("userName")));
        if (user == null) {
            return new Result().setMsg("用户不存在").setCode(403);
        }
        //获取用户的盐，对密码进行加密
        String salt = user.getSalt();
       password = new Md5Hash(password, salt).toString();
        user.setPassword(password);
        boolean update = userService.updateById(user);
        return new Result().setSuccess(update);
    }


    /**
     * 告诉前端跳转角色分配权限
     * @param id
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/to_assignment_role",params = "id")
    public Result toAssignmentRole(String id) throws Exception {
        //查询所有的角色
        List<TRole> allRoles = roleService.list();
        //查询当前用户拥有的角色
        List<TRole> roles = userRoleService.getRolesByUserId(id);
        List<String> roleIds = roles.stream().map(e -> e.getId()).collect(Collectors.toList());
        HashMap<String, Object> map = new HashMap<>();
        map.put("roles",allRoles);
        map.put("userRoleIds",roleIds);
        return new Result().setData(map).setSuccess(true);
    }

    /**
     * 分配角色
     * @param id
     * @param roleIds
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/assignment_role",params = {"id"},method = RequestMethod.PUT)
    @Authority(auth = "account:user:role")
    public Result assignmentRole(String id, @RequestBody String[] roleIds)throws Exception{
        if (id == null){return new Result().setMsg("参数不能为空");}

        TUser user = userService.getById(id);
        if (user==null){return new Result().setMsg("用户不存在");}
        //获取全部的角色id集合
        List<String> allRoleIds = roleService.list()
                .stream()
                .map(e -> e.getId())
                .collect(Collectors.toList());
        //过滤数据库不存在的角色id，并去重转换为集合
        List<String> roleIDList = Arrays.stream(roleIds)
                .filter(e -> allRoleIds.contains(e))
                .distinct()
                .collect(Collectors.toList());

        boolean result = userRoleService.BatchSave(id,roleIDList);
        return new Result().setSuccess(result);
    }



}
